package com.order.common.filter;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.order.common.entiry.ResultCode;
import com.order.common.entiry.ResultEntity;
import com.order.common.exception.CommonException;
import com.order.controller.BaseController;
import com.order.service.UserService;
import com.order.service.impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

@WebFilter(filterName = "ApplicationFilter", urlPatterns = "/*")
public class ApplicationFilter implements Filter {

    private UserService userService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        userService = new UserServiceImpl();

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 设置允许跨域访问的域名，* 表示允许所有域名
        response.setHeader("Access-Control-Allow-Origin", "*");
        // 设置允许客户端发送的请求头
        response.setHeader("Access-Control-Allow-Headers", "Content-Type");
        // 设置允许客户端发送的请求方法
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
        // 设置预检请求的有效期，单位是秒
        response.setHeader("Access-Control-Max-Age", "3600");

        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return;  // Stop the filter chain for OPTIONS request
        }
        // 统一编码设置
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        try {
        filterChain.doFilter(request, response);
        } catch (CommonException e) {
            BaseController baseController = new BaseController();
            baseController.writeResult(response, e.getResultCode());
        }
        catch (Exception e) {
            BaseController baseController = new BaseController();
            baseController.writeResult(response, ResultCode.SERVER_ERROR);
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
